﻿using System.Linq;
using CustomerContactSystem.Core.Infrastructure.DataAccess;
using CustomerContactSystem.Core.Infrastructure.Domain;
using NHibernate;
using NHibernate.Linq;

namespace CustomerContactSystem.Core.DataAccess.nHibernate {
    public class NhibernateRepository<T> : INhibernateRepository<T> where T : Entity {
        private readonly ISession _session;

        public NhibernateRepository(ISession session) {
            _session = session;
        }

        public ISession Session {
            get { return _session; }
        }

        public IQueryable<T> Query() {
            return _session.Query<T>();
        }

        public IQueryOver<T, T> QueryOver() {
            return _session.QueryOver<T>();
        }

        public void Add(T entity) {
            using (var tx = _session.BeginTransaction()) {
                _session.Save(entity);
                tx.Commit();
            }
        }

        public void Update(T entity) {
            using (var tx = _session.BeginTransaction()) {
                _session.Update(entity);
                tx.Commit();
            }
        }

        public void Delete(T entity) {
            using (var tx = _session.BeginTransaction()) {
                _session.Delete(entity);
                tx.Commit();
            }
        }

        public T GetById(object id) {
            return _session.Get<T>(id);
        }

        public T LoadReference(object id) {
            return _session.Load<T>(id);
        }
    }
}